package nmcli

import (
	"fmt"
	"os/exec"
	"strings"
)

// IpDefaults settings to apply to an existing NetworkManager connection
type IpDefaults struct {
	DNS         string
	Ipv4Address string
	Ipv4Gateway string
	IgnoreIPV6  bool
}

//nmcli connection modify enp3s0 ipv4.method manual ipv4.addresses 35.37.33.50/27 ipv4.gateway 35.37.33.62 ipv4.dns 114.114.114.114 ipv4.ignore-auto-dns true
//nmcli connection modify "有线连接 1" ipv4.method manual ipv4.addresses 35.37.33.50/27 ipv4.gateway 35.37.33.62 ipv4.dns 114.114.114.114 ipv4.ignore-auto-dns true

// ModifyConnection modifies the connectionID Ip
func ModifyIp(connectionID string, settings IpDefaults) ([]string, error) {
	if err := checkHasNmcli(); err != nil {
		return nil, err
	}

	execCmd := []string{
		"connection",
		"modify", connectionID,
		"ipv4.method manual",
		fmt.Sprintf("ipv4.addresses %s", settings.Ipv4Address),
		fmt.Sprintf("ipv4.gateway %s", settings.Ipv4Gateway),
		fmt.Sprintf("ipv4.dns %s", settings.DNS),
		"ipv4.ignore-auto-dns true",
	}

	var cmdFields []string
	for key, cmd := range execCmd {
		if key == 2 {
			cmdFields = append(cmdFields, cmd)
		} else {
			cmdFields = append(cmdFields, strings.Fields(cmd)...)
		}

	}
	//loglog.Handler.Info("running nmcli %v", cmdFields)
	cmd := exec.Command("nmcli", cmdFields...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out pipe produced err")
		return nil, err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out err produced")
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		//loglog.Handler.Warn("cmd failed to start")
		return nil, err
	}

	data := GetStdoutText(stdout)
	if errOut := GetStdoutText(stderr); errOut != nil {
		return nil, fmt.Errorf(strings.Join(errOut, " "))
	}

	cmd.Wait()
	return data, err

}

// 添加或者删除ip地址
func AddOrDeleteIp(connectionID string, ip, mask string, operation string) ([]string, error) {
	if err := checkHasNmcli(); err != nil {
		return nil, err
	}

	execCmd := []string{
		"connection",
		"modify", connectionID,
		fmt.Sprintf("%sipv4.addresses %s/%d", operation, ip, StringIpToInt(mask)),
	}

	var cmdFields []string
	for key, cmd := range execCmd {
		if key == 2 {
			cmdFields = append(cmdFields, cmd)
		} else {
			cmdFields = append(cmdFields, strings.Fields(cmd)...)
		}

	}
	//loglog.Handler.Info("running nmcli %v", cmdFields)
	cmd := exec.Command("nmcli", cmdFields...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out pipe produced err")
		return nil, err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		//loglog.Handler.Warn("cmd out err produced")
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		//loglog.Handler.Warn("cmd failed to start")
		return nil, err
	}

	data := GetStdoutText(stdout)
	if errOut := GetStdoutText(stderr); errOut != nil {
		return nil, fmt.Errorf(strings.Join(errOut, " "))
	}

	cmd.Wait()
	return data, err
}
